class ChurchesController < ApplicationController
  before_filter :find_church, :only => [ :show,
                                          :edit,
                                          :update,
                                          :destroy]

  helper_method :sort_column, :sort_direction
  
  # GET /churches
  # GET /churches.json
  def index
    @churches = Church.search(params[:search]).order(sort_column + " " + sort_direction).page(params[:page])
    if params[:recent] == "true"
      @churches = @churches.recent
    end

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @churches }
    end
  end

  # GET /churches/1
  # GET /churches/1.json
  def show
    @church = Church.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @church }
    end
  end

  # GET /churches/new
  # GET /churches/new.json
  def new
    @church = Church.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @church }
    end
  end

  # GET /churches/1/edit
  def edit
    @church = Church.find(params[:id])
  end

  # POST /churches
  # POST /churches.json
  def create
    @church = Church.new(params[:church])

    respond_to do |format|
      if @church.save
        format.html { redirect_to @church, notice: 'Church was successfully created.' }
        format.json { render json: @church, status: :created, location: @church }
      else
        format.html { render action: "new" }
        format.json { render json: @church.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /churches/1
  # PUT /churches/1.json
  def update
    @church = Church.find(params[:id])

    respond_to do |format|
      if @church.update_attributes(params[:church])
        format.html { redirect_to @church, notice: 'Church was successfully updated.' }
        format.json { head :ok }
      else
        format.html { render action: "edit" }
        format.json { render json: @church.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /churches/1
  # DELETE /churches/1.json
  def destroy
    @church = Church.find(params[:id])
    @church.destroy
    flash[:notice] = "Church has been deleted."

    respond_to do |format|
      format.html { redirect_to churches_url }
      format.json { head :ok }
    end
  end
  
  private
    def find_church
      @church = Church.find(params[:id])
      rescue ActiveRecord::RecordNotFound
      
      respond_to do |format|
        format.html { redirect_to churches_url, alert: 'The church you were looking for could not be found.'  }
        format.json { render json: @church.errors, status: :unprocessable_entity }
      end
    end
    
    def sort_column
      Church.column_names.include?(params[:sort]) ? params[:sort] : "name"
    end
  
    def sort_direction
      %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
    end
end
